const { execSync } = require('child_process');
const fs = require('fs-extra');
const path = require('path');

// 清理子模块目录
function cleanSubmoduleDirectory(submodulePath) {
    console.log(`Cleaning submodule directory: ${submodulePath}`);
    fs.emptyDirSync(submodulePath);
}

// 初始化并更新子模块
console.log('Initializing and updating submodules...');
execSync('git submodule update --init --recursive');

// 清理子模块目录
const submodulePath = path.join(__dirname, 'website');
if (fs.existsSync(submodulePath)) {
    cleanSubmoduleDirectory(submodulePath);
}

// 编译构建网站
console.log('Installing dependencies...');
execSync('npm install');

console.log('Building website...');
execSync('npm run build');

// 复制生成的网站文件到子模块
const sourceDir = path.join(__dirname, 'build');
const targetDir = submodulePath;
console.log(`Copying files from ${sourceDir} to ${targetDir}...`);
fs.copySync(sourceDir, targetDir);

// 进入子模块目录
process.chdir(targetDir);

// 定义提交并推送更改的函数，接受一个自定义的 commit_message 参数
function commitAndPush(commitMessage, defaultMessage) {
    const defaultMsg = defaultMessage || 'new build';
    const message = commitMessage || defaultMsg;

    // 添加所有文件到暂存区
    console.log('Adding files to the staging area...');
    execSync('git add .');

    // 获取当前时间
    const currentTime = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');

    // 获取操作系统类型和名称
    const osInfo = `${process.platform} ${process.version}`;

    // 配置Git用户身份（这里改为局部配置，仅针对本次会话）
    console.log('Configuring Git user identity...');
    execSync('git config --local user.email "succpeking@foxmail.com"');
    execSync('git config --local user.name "kyle"');

    // 提交更改，使用传入的 commit_message 并包含当前时间和系统信息
    console.log('Committing changes...');
    execSync(`git commit -m "${message}: ${currentTime} (${osInfo})"`);

    // 推送到远程仓库
    console.log('Pushing changes to the remote repository...');
    execSync('git push origin master');
    console.log('Changes have been successfully pushed to the remote repository.');
}

// 更新 submodule 仓库 website，使用用户提供的 message 或默认的 "new build" 消息
console.log('Updating submodule repository...');
commitAndPush(process.argv[2], 'new build');

// 返回主仓库目录
process.chdir(__dirname);

// 更新源数据仓库，使用用户提供的 message 或默认的 "new data" 消息
console.log('Updating main repository...');
commitAndPush(process.argv[2], 'new data');
